import React, { PureComponent } from 'react'
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import { Select, Button, Dropdown, Menu, Modal } from 'antd'
import dayjs from "dayjs";
import ParamsInput from "@common/presentational/ParamsInput";
import { PROMOTION_NAME_TYPE, PROMOTION_STATUS, PROMOTION_STATUS_MAP } from '@constants/ActivityListMap'
import { getPromotion, getPromotionDetail, pausePromotion, resumePromotion, publishPromotion } from '@sagas/marketing'
import marketArrayParams from '@utils/marketArrayParams'
import DropdownMenu from "@common/presentational/DropdownMenu";
import { getQuery, handleQueryEqual, setQuery, getHistoryMatchParams } from "@utils/setUrlQuery";
import CustomizeTableProvide, { CustomizeTable, CustomizeTablePagination } from "@common/presentational/CustomizeTable";
import {priceFenToYuan, priceYuanToFen} from "@utils/priceConversion";
import {
   setHeaderBreadCrumbInfo
} from "@sagas/common";
import PromotionStatsModal from '@components/marketing/modal/PromotionStatsModal'
import BilinIcon from "@common/presentational/BilinIcon";

@withRouter
@connect(({ marketing }) => ({
   allPromotion: marketing.allPromotion,
}), {
       setHeaderBreadCrumbInfo,
       getPromotion,
       getPromotionDetail,
       pausePromotion,
       resumePromotion,
       publishPromotion
   }
)
class MarketingPromotionPage extends PureComponent {
   constructor(props) {
       super(props);
       const {
           status = '',
           keyword = '',
       } = getQuery(props.history)
       const { type } = getHistoryMatchParams(props)
       this.state = {
           type,
           status,
           keyword
       }

       this.tableRef = React.createRef()
       this.promotionStatsModalRef = React.createRef()
       this.getTableInfo = this.getTableInfo.bind(this)
       this.modifyPromotion = this.modifyPromotion.bind(this)
       this.resumePromotion = this.resumePromotion.bind(this)
       this.pausePromotion = this.pausePromotion.bind(this)

       this.paginationInfo = {}
       this.columns = [{
           dataIndex: 'name',
           key: 'name',
           title:'活动名称',
           width: 180,
           render: (text, record) => record.self.name
       },{
            dataIndex: 'offer_type',
            key: 'offer_type',
            title:'类型',
            width: 100,
            render: (text, record) => PROMOTION_NAME_TYPE[record.self.offer_type]
        },{
           dataIndex: 'content',
           key: 'content',
           title:'活动内容',
           render:(text, record) =>{
               if(type === 'quota_cut'){
                   if(record.self.gradient_rules.length){
                       return record.self.gradient_rules.map(item=>`满${priceFenToYuan(item.quota)}元 减${priceFenToYuan(item.price)}元`).join('、')
                   }else{
                       return `每满${priceFenToYuan(record.self.quota)}元 减${priceFenToYuan(record.self.price)}元`
                   }
               }
               if(type ==='discount'){
                    return `${record.self.quota? `满${priceFenToYuan(record.self.quota)}元` : ''} 打${record.self.price/10}折 ${record.self.off_maximum? `最多优惠${priceFenToYuan(record.self.off_maximum)}元` : ''}`
               }
           }
       },{
           dataIndex: 'promotion_status',
           key: 'promotion_status',
           title:'状态',
           width: 80,
           render: (text, record)=>PROMOTION_STATUS[record.self.promotion_status]
       },{
           dataIndex: 'times',
           key: 'times',
           title:'有效时间',
           width: 250,
           render:(text, record) =>{
               return <div>{dayjs(record.self.begined).format('YYYY-MM-DD')} ～ {dayjs(record.self.ended).format('YYYY-MM-DD')}</div>
           }
       },{
           dataIndex: 'options',
           key: 'options',
           title:'操作',
           render: (text, record) => {
               let dropList = [{
                   key: 'modify',
                   name: '编辑',
               }];
               if(record.self.promotion_status === 'paused'){
                   dropList.push({
                       key: 'resume',
                       name: '启用',
                   })
               }
               if(record.self.promotion_status === 'published'){
                   dropList.push({
                       key: 'pause',
                       name: '停用',
                   })
               }
               return (
                   <div className="flex-vertical-center">
                       {record.self.promotion_status === 'draft' && <div onClick={this.publishPromotion.bind(this,record)} className="mgr-8 ft-hover">发布</div>}
                       <div onClick={this.showStat.bind(this,record)} className="mgr-8 ft-hover">数据</div>
                       <DropdownMenu
                           dropdownList={dropList}
                           onClick={this.handleRowOperation.bind(this, record)}
                       >
                           <div className="ft-hover">更多</div>
                       </DropdownMenu>
                   </div>
               )
           }
       } ]
   }

   publishPromotion(record){
       const { publishPromotion } = this.props
       const that = this
       Modal.confirm({
           title: '确认发布？',
           icon: null,
           onOk: ()=>{
               publishPromotion({
                   id: record.self.id
               }, () => {
                   that.getTableInfo()
               })
           }
       })
   }
   
   resumePromotion(record){
       const { resumePromotion } = this.props
       const that = this
       Modal.confirm({
           title: '是否确认启用',
           icon: null,
           onOk: ()=>{
               resumePromotion({
                   id: record.self.id
               }, () => {
                   that.getTableInfo()
               })
           }
       })
   }

   pausePromotion(record){
       const { pausePromotion } = this.props
       const that = this
       Modal.confirm({
           title: '是否确认停用',
           icon: null,
           // content:<></>,
           onOk: ()=>{
               pausePromotion({
                   id: record.self.id
               }, () => {
                   that.getTableInfo()
               })
           }
       })
   }

   modifyPromotion(record){
       const { getPromotionDetail, history } = this.props
       getPromotionDetail({
           id: record.self.id
       }, (res) => {
           history.push({
               pathname: `/marketing/promotion/${record.self.offer_type}/modify/${record.self.id}`,
               state: {
                   ...res.promotion
               }
           })
       })
   }

   showStat(record){
       this.promotionStatsModalRef.current?.show({
           ...record.stat
       })
   }

   handleRowOperation(record, type) {
       switch (type) {
           case 'resume':
               this.resumePromotion(record)
               break;
           case 'pause':
               this.pausePromotion(record)
               break;
           case 'modify':
               this.modifyPromotion(record)
               break;
           default:
               break;
       }
   }

   componentDidMount(){
       const { type } = this.state
       this.props.setHeaderBreadCrumbInfo([{
           text: '营销',
           link: '/marketing',
       },{
           text: PROMOTION_NAME_TYPE[type],
           link: '',
       }])
   }

   componentWillUnmount () {
       this.props.setHeaderBreadCrumbInfo(null)
   }

   handleValueChange (key, value) {
       this.setState({
           [key]: value
       }, this.initTable)
   }

   getTableInfo ({ current, pageSize } = this.paginationInfo) {
       this.paginationInfo = { current, pageSize }
       const { status, keyword, type } = this.state
       const params = {
           pageNo: current,
           pageSize,
           offer_types:marketArrayParams(type)
       }
       if(status){
           params.promotion_statuses = marketArrayParams(status)
       }
       if(keyword){
           params.keyword = keyword
       }
       this.props.getPromotion(params)
       this.setUrlQuery()
   }

   initTable () {
       this.tableRef.current?.initPage()
   }

   setUrlQuery () {
       const { status, keyword } = this.state
       const { history } = this.props
       let params = { status, keyword }
       handleQueryEqual(params, history) || setQuery(params, history)
   }

   create(){
       const { type } = this.state
       const { history } = this.props
       history.push(`/marketing/promotion/${type}/create`)
   }

    render() {
        const { status, keyword } = this.state
        const { allPromotion } = this.props
        return (
            <div className='marketing-page table-scroll-container'>
               <div className="table-params page-params flex-row-between mgb-16">
                   <div className="flex-vertical-center">
                        <Button onClick={this.create.bind(this)} type="primary" className="button-small mgr-16"><BilinIcon type="plus" className="ft-18 mgr-8"/>新建活动</Button>
                   </div>
                   <div className="flex-vertical-center">
                   <Select
                       style={{width: '140px'}}
                       onChange={this.handleValueChange.bind(this, 'status')}
                       value={status}
                   >
                       <Select.Option key="" value="">全部状态</Select.Option>
                       {PROMOTION_STATUS_MAP.map(item=>{
                           return(<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>)
                       })}
                   </Select>
                   <ParamsInput
                       className="mgl-16"
                       style={{width: '140px'}}
                       value={keyword}
                       onChange={this.handleValueChange.bind(this, 'keyword')}
                       placeholder="活动名称"
                   />
                   </div>
               </div>
               <CustomizeTableProvide ref={this.tableRef} tableKey="promotionList" onChange={this.getTableInfo}>
                   <div className="table-list">
                       <CustomizeTable
                           columns={this.columns}
                           dataSource={allPromotion.rows || []}
                       />
                   </div>
                   <div className="table-pagination">
                       <CustomizeTablePagination
                           total={allPromotion.total}
                       />
                   </div>
               </CustomizeTableProvide>
               <PromotionStatsModal ref={this.promotionStatsModalRef} />
            </div>
        )
    }
}

export default MarketingPromotionPage